<?php

namespace App\Http\Controllers\Front;

use App\Model\Articles;
use App\Model\Cards;
use App\Model\PersonalPageTemplateUser;
use App\Model\UserInterPushInfo;
use App\Model\UserInterPushRecord;
use App\Model\UserInterPushRecordMaterial;
use App\Model\UserMarketing;
use App\Model\UserMsg;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Swagger\Annotations as SWG;

class UserInterPushController extends Controller
{
    private  $user;
    private  $interPushCity;
    private  $interPushNum;
    private  $redis;

    public function __construct()
    {
        $this->user = \Auth::user();
        $this->interPushCity = date('Ymd')."_" .$this->user->interPushInfo->province_id.'_city';
        $this->interPushNum = "user_id_".$this->user->interPushInfo->id; // 今天使用互推圈次数
        $this->redis = Redis::connection();
        $this->redis->select (0);
    }

    //region 互推圈列表
    /**
     * @SWG\Get(
     *     path="/front/inter_push/list",
     *     tags={"互推圈"},
     *     summary="获取互推列表",
     *     description = "互推列表",
     *     consumes={"application/form-data"},
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *     response="200",
     *     description="互推用户列表",
     *          @SWG\Schema(
     *                type="array",
     *                   @SWG\Items(
     *                    @SWG\Property(property="id", type ="integer", description ="用户id"),
     *                    @SWG\Property(property="head_picture", type="string", description="用户头像")
     *              )
     *          )
     *     )
     * )
     *
     */
    public function getUserInterPushList()
    {
        $interPushInfo =  $this->user->interPushInfo;
        //用户昨天（凌晨12点）的分享任务是否完成， 判断用户互推次数是否用完
//        $is_count =  $interPushInfo->passiveInterPushRecord()->whereRaw("DATE(`created_at`) < curdate()")->count();
//        if ($is_count >0){
//            return $this->fail("请完成分享任务！");
//        }
//        if($this->redis->get($this->interPushNum) == 0 || $this->redis->exists($this->interPushNum) == false){
//            if (User::where("pid","=", $this->user->id)->count() < 10){
//                return $this->fail("今天的次数已经用完, 请邀请好友加入！");
//            }
//            return $this->fail("今天的次数已经用完");
//        }
        $inter_push_info_id = $this->redis->srandmember($this->interPushCity, 24);
        // todo 主动查找当天已经匹配过和被分享过的用户
        $already_user_id = $interPushInfo->interPushRecord()
            ->whereRaw("(DATE(`created_at`) = curdate() or DATE(`updated_at`) = curdate() or target_is_share = 0)")
            ->pluck("target_interpush_id")
            ->toArray();
//        $yesterday_user_id = $interPushInfo->interPushRecord()
//            ->where ("target_is_share", '=', 0)
//            ->pluck("target_meterial_id")
//            ->toArray();

        // todo 查找被动任务
        $passive_already_user_id = $interPushInfo->passiveInterPushRecord()
            ->whereRaw("(DATE(`created_at`) = curdate() or DATE(`updated_at`) = curdate() or target_is_share= 0)")
            ->pluck("interpush_id")
            ->toArray();
//        $passive_yesterday_user_id = $interPushInfo->passiveInterPushRecord()
//            ->where ("target_is_share", '=', 0)
//            ->pluck("meterial_id")
//            ->toArray();
        // 判断自己是否在里面
        array_push ($already_user_id, $interPushInfo->id);
//        $count_user_id  =  array_merge ($already_user_id, $yesterday_user_id);
//        $count_passive_user_id = array_merge ($passive_already_user_id, $passive_yesterday_user_id);
        if (count ($already_user_id) > 0 ){
            $inter_push_info_id = array_diff ($inter_push_info_id, $already_user_id,$passive_already_user_id);
        }
        //获取user_id
        $user_id =  UserInterPushInfo::with("user")
            ->where("is_enabled", "=", 1)
            ->whereIn ("id",$inter_push_info_id)
            ->pluck ("user_id");

        $user =  DB::table("users")
            ->leftJoin("cards","users.id","=","cards.user_id")
            ->leftJoin("user_detail","users.id","=","user_detail.user_id")
            ->whereIn("users.id",$user_id)
            ->select("users.id","cards.head_picture", "user_detail.head_portrait")
            ->get();

        return $this->renderJson ($user);
    }

    //endregion
    // region 获取登陆用户互推信息
    /**
     * @SWG\Get(
     *     path="/front/inter_push/get_info/",
     *     tags={"互推圈"},
     *     summary="获取登录用户互推信息",
     *     description="获取登录用户互推信息",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", type="integer", description="用户id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功！",
     *          @SWG\Schema(
     *                @SWG\Property(property="user_id", type="integer", description="用户id"),
     *                @SWG\Property(property="name", type="string", description="用户名称"),
     *                @SWG\Property(property="head_picture", type="string", description="用户头像"),
     *                @SWG\Property(property="phone", type="string", description="用户电话号码"),
     *                @SWG\Property(property="use_num", type="integer", description="使用互推圈次数"),
     *                @SWG\Property(property="others_browse_num", type="integer", description="为他人带来浏览次数"),
     *                @SWG\Property(property="forme_brows_num", type="integer", description="他人为我带来浏览次数"),
     *                @SWG\Property(property="material_style", type="integer", description="1,文章，2个人网页，3，营销网页，4，个人名片"),
     *                @SWG\Property(property="share_num", type="integer", description="登陆用户使用互推圈次数"),
     *                @SWG\Property(property="province_id", type="integer", description="地区id"),
     *                @SWG\Property(property="province", type="string", description="地区名称"),
     *                @SWG\Property(property="material_id", type="integer", description="素材id有可能为空"),
     *                @SWG\Property(property="is_enabled", type="integer", description="启用1， 0禁用"),
     *                @SWG\Property(property="share_passive_num", type="integer", description="分享任务"),
     *                @SWG\Property(property="today_share_num", type="integer", description="今天分享次数"),
     *          )
     *      )
     * )
     *
     */
    public function getUserInterPush()
    {
        $user = User::whereId($this->user->id)->first();
        // 互推类容
        $interPushInfo = $user->interPushInfo;
        $interPushInfoMaterial = $this->getUserMeterial($interPushInfo->material_style, $interPushInfo->material_id);
        // 分享任务
        $share_passive_num =  $interPushInfo
            ->passiveInterPushRecord()
            ->where("target_is_share", "=", 0 )
            ->count();
        $yesterday_share_passive_num =  $interPushInfo
            ->passiveInterPushRecord()
            ->where("target_is_share", "=", 0 )
            ->whereRaw("DATE(`created_at`) < curdate()")
            ->count();

        // 查找今天分享了几次
        $num = $interPushInfo->interPushRecord()
            ->whereRaw("DATE(`created_at`) = curdate()")
            ->count();

        $data = [
            'user_id' => $user->id,
            'name' => isset($user->cards)? $user->cards->user_name : "",
            'head_picture' => isset($user->cards) ? $user->cards->head_picture : "",
            'phone' => $user->phone,
            'use_num' => $interPushInfo->use_num,
            'province_id'=>$interPushInfo->province_id,
            'province' => $interPushInfo->province,
            'others_browse_num' => $interPushInfo->others_browse_num,
            'forme_brows_num'=> $interPushInfo->forme_brows_num,
            'material_style' => $interPushInfo->material_style,
            'material_id'=>$interPushInfoMaterial->id,
            'is_enabled' => $interPushInfo->is_enabled,
            'share_num' => $interPushInfo->num, //  每天使用次数
            'today_share_num' =>  ($interPushInfo->num - $num) > 0 ? $interPushInfo->num - $num : 0, // 今天分享次数
            'share_passive_num'=>$share_passive_num, // 分享任务
            'interPushInfoMaterial' =>$interPushInfoMaterial,
            'yesterday_share_passive_num' => $yesterday_share_passive_num, // 昨天的分享任务
        ];
        return $this->renderJson ($data);
    }

    //endregion

    //region 获取互推用户互推详情
    /**
     * @SWG\Get(
     *     path="/front/inter_push/info/{id}",
     *     tags={"互推圈"},
     *     summary="点击获取互推用户信息",
     *     description="根据用户id获取互推信息",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", type="integer", description="用户id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功！",
     *          @SWG\Schema(
     *                @SWG\Property(property="user_id", type="integer", description="用户id"),
     *                @SWG\Property(property="name", type="string", description="用户名称"),
     *                @SWG\Property(property="head_picture", type="string", description="用户头像"),
     *                @SWG\Property(property="phone", type="string", description="用户电话号码"),
     *                @SWG\Property(property="use_num", type="integer", description="使用互推圈次数"),
     *                @SWG\Property(property="others_browse_num", type="integer", description="为他人带来浏览次数"),
     *                @SWG\Property(property="material_style", type="integer", description="1,文章，2个人网页，3，营销网页，4，个人名片"),
     *                @SWG\Property(property="share_num", type="integer", description="登陆用户使用互推圈次数"),
     *                @SWG\Property(property="interPushInfoMaterial", type="object", description="互推素材,文章，个人网页，营销网页， 名片",
     *                      @SWG\Property(property="article", type="object", description="文章article字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="author", type="integer", description="作者id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="personal_page_template_user", type="object", description="个人网页，personal_page_template_user字段实际中没有只是文档中作区分",
     *                           @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="user_marketing", type="object", description="营销网页，user_marketing字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="cards", type="object", description="名片cards，cards字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="head_picture", type="string", description="头像"),
     *                          @SWG\Property(property="logo", type="string", description="logo"),
     *                          @SWG\Property(property="user_name", type="string", description="用户名称"),
     *                          @SWG\Property(property="motto", type="string", description="封面"),
     *                          @SWG\Property(property="company", type="string", description="公司"),
     *                          @SWG\Property(property="sex", type="int", description="性别1男2女"),
     *                          @SWG\Property(property="province", type="int", description="省id"),
     *                          @SWG\Property(property="city", type="int", description="市id"),
     *                          @SWG\Property(property="area", type="int", description="区id"),
     *                          @SWG\Property(property="address_detail", type="string", description="详细地址"),
     *                      ),
     *                ),
     *
     *          )
     *      )
     * )
     *
     */

    public function getUserInterPushById($id)
    {
        $user = User::whereId($id)->first();
//        $currentUserInterPushInfo = $this->user->interPushInfo;
//        $share_num = $currentUserInterPushInfo->num - $currentUserInterPushInfo->interPushRecord()
//            ->whereRaw("DATE(`created_at`) < curdate()")
//            ->count();
        // 互推类容
        $interPushInfo = $user->interPushInfo;
        $interPushInfoMaterial = $this->getUserMeterial($interPushInfo->material_style, $interPushInfo->material_id);


        $data = [
            'user_id' => $user->id,
            'name' => isset($user->cards)? $user->cards->user_name : "",
            'head_picture' => $user->portrait(),
            'phone' => $user->phone,
            'use_num' => $interPushInfo->use_num,
            'others_browse_num' => $interPushInfo->others_browse_num,
            'material_style' => $interPushInfo->material_style,
//            'share_num' => $share_num,
            'interPushInfoMaterial' =>$interPushInfoMaterial
        ];
        return $this->renderJson ($data);
    }

    //endregion
    //region 生成互推信息
    /**
     * @SWG\Post(
     *     path="/front/inter_push/add",
     *     tags={"互推圈"},
     *     summary="生成互推记录",
     *     description="生成互推记录",
     *     produces={"application/form-data"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="user_id", in="formData", required=true, type="integer", description="用户id"),
     *     @SWG\Parameter(name="material_style", in="formData", required=true, type="integer", description="素材类型1,文章，2个人网页，3营销网页， 4名片"),
     *     @SWG\Parameter(name="material_id", in="formData", required=true, type="integer", description="素材id"),
     *     @SWG\Response(
     *          response="200",
     *          description="分享成功",
     *          @SWG\Property(property="record_id", type="integer", description="记录id"),
     *          @SWG\Property(property="interpush_id", type="integer", description="用户互推信息id"),
     *      )
     *
     * )
     */
    public function saveUserInterPushRecord(Request $request)
    {
        $this->validate($request,[
            'user_id' =>  'required|numeric',
            'material_style' =>  'required|numeric',
            'material_id' =>  'required|numeric',
            'target_user_id' =>  'required|numeric',
            'target_material_style' =>  'required|numeric',
            'target_material_id' =>  'required|numeric',
        ],[
            'user_id.required' => 'user_id不能为空',
            'user_id.numeric' => 'user_id必须是数字',
            'material_style.required' => 'material_style不能为空',
            'material_style.numeric' => 'material_style必须是数字',
            'material_id.required' => 'material_id不能为空',
            'material_id.numeric' => 'material_id必须是数字',
            'target_user_id.required' => 'target_user_id不能为空',
            'target_user_id.numeric' => 'target_user_id必须是数字',
            'target_material_style.required' => 'target_material_style不能为空',
            'target_material_style.numeric' => 'target_material_style必须是数字',
            'target_material_id.required' => 'target_material_id不能为空',
            'target_material_id.numeric' => 'target_material_id必须是数字',
        ]);

        $targetUser = User::whereId ($request->input ("target_user_id"))->first(); // 目标用户
        $targetInterPushUserInfo = $targetUser->interPushInfo; // 目标用户互推信息
        $target_redis_inter_push_info_id = "user_id_".$targetInterPushUserInfo->id;
        $interPushUserInfo = $this->user->interPushInfo; // 获取登录用户互推信息

        // 查看用户被匹配次数是否用完
        if ($this->redis->exists($target_redis_inter_push_info_id) == false){
            return $this->fail("对方今日被匹配次数已用完，请换一个互推用户！");
        }

        // 查看用户今天是否被匹配过（防止重复提交）
        $count =$interPushUserInfo->interPushRecord()
            ->where("target_interpush_id", "=", $targetInterPushUserInfo->id)
            ->WhereRaw("DATE(`created_at`) = curdate() ")
            ->count();
          if ($count > 0){
             return $this->fail("今天已经匹配过对方，不能互推！");
          }
          $toDayCount = $interPushUserInfo->interPushRecord()->WhereRaw("DATE(`created_at`) = curdate() ")->count();

          if ($interPushUserInfo->num == $toDayCount){
              return $this->fail("今天互推次数已经用完！");
          }

        // todo 扣除目标用户redis次数
        if ($this->redis->decr($target_redis_inter_push_info_id) == 0){
            if ($targetInterPushUserInfo->province_id != 0){
                $this->redis->srem(date('Ymd')."_0_city",$targetInterPushUserInfo->id ); //移除 全国
            }
            $this->redis->srem (date('Ymd')."_".$targetInterPushUserInfo->province_id."_city", $targetInterPushUserInfo->id ); // 移除 具体地区
            $this->redis->del($target_redis_inter_push_info_id); // 删除次数
        }
        // 添加用户互推信息
        $material_style =  $request->input("target_material_style");
        $material_id = $request->input("target_material_id");
        $interPushUserMaterial = $this->getUserMeterial($material_style, $material_id);

        // 自己的互推信息
        try{
            DB::beginTransaction ();
            // todo 对方 添加互推信息（素材）
            $interPushUserMaterialId =    UserInterPushRecordMaterial::insertGetId([
                'user_name' => $targetUser->name(),
                'user_id'   => $request->input ("target_user_id"),
                'head_portrait' => $targetUser->portrait(),
                'cover' => isset($interPushUserMaterial->cover) ? $interPushUserMaterial->cover : "",
                'title' => $material_style == 4 ? str_replace("\\/", "/",json_encode($interPushUserMaterial->toArray(), JSON_UNESCAPED_UNICODE)) : $interPushUserMaterial->title,
                'source_type' => $interPushUserMaterial->getMorphClass(),
                'source_id' => $interPushUserMaterial->id,
                'source_style' => $material_style,
                'created_at' => Carbon::now (),
            ]);
            // todo 自己的互推信息
            $userMaterial = $this->getUserMeterial($request->input("material_style"), $request->input("material_id"));
            $userMaterialId =  UserInterPushRecordMaterial::insertGetId([
                'user_name' => $this->user->name(),
                'user_id'   => $this->user->id,
                'head_portrait' => $this->user->portrait(),
                'cover' => isset($userMaterial->cover) ? $userMaterial->cover :"",
                'title' => $interPushUserInfo->material_style == 4 ?  str_replace("\\/", "/",json_encode($userMaterial->toArray(), JSON_UNESCAPED_UNICODE)) : $userMaterial->title,
                'source_type' => $userMaterial->getMorphClass(),
                'source_id' => $userMaterial->id,
                'source_style' => $request->input("material_style"),
                'created_at' => Carbon::now (),
            ]);
            //添加互推记录
            $interPushRecord = new  UserInterPushRecord();
            $interPushRecord->interpush_id = $this->user->interPushInfo->id;
            $interPushRecord->meterial_id = $userMaterialId;
            $interPushRecord->is_share = 1;
            $interPushRecord->share_time = Carbon::now();
            $interPushRecord->target_interpush_id = $targetUser->interPushInfo->id;
            $interPushRecord->target_meterial_id = $interPushUserMaterialId;
            $interPushRecord->save();
            // todo 添加自己使用次数
            $this->user->interPushInfo->increment("use_num");
            DB::commit ();
        }catch (\Exception $exception){
            \Log::error ($exception);
            DB::rollBack();
            echo $exception;
            return $this->fail("互推失败!");
        }
        return $this->renderJson([
            'record_id' => $interPushRecord->id,
            'interpush_id' => $targetUser->interPushInfo->id,
        ]);
//        return $this->success ("");
    }

    //endregion

    //region 获取用户分享记录
    /**
     * @SWG\Get(
     *     path="/front/inter_push/share_list",
     *     tags={"互推圈"},
     *     summary="分享记录，分享任务",
     *     description="分享记录列表",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="type", in="path", type="integer", description="1相互已经分享，2对方没有分享，3我的分享任务"),
     *     @SWG\Response(
     *     response="200",
     *     description="响应成功",
     *          @SWG\Schema(
     *                  @SWG\Property(property="id", type="integer", description=""),
     *                  @SWG\Property(property="user_id", type="integer", description="用户id"),
     *                  @SWG\Property(property="province_id", type="integer", description="地区id"),
     *                  @SWG\Property(property= "province", type="string", description="地区名称"),
     *                  @SWG\Property(property="use_num", type="integer", description="使用次数"),
     *                  @SWG\Property(property="others_browse_num", type="integer", description="为他人带来次数"),
     *                  @SWG\Property(property="is_enabled", type="integer", description="启用1， 0 禁用"),
     *                  @SWG\Property(property="inter_push_record", type="object", description="我匹配用户",
     *                      @SWG\Property(property="id", type="integer", description="启用1， 0 禁用"),
     *                      @SWG\Property(property="interpush_id", type="integer", description="互推id"),
     *                      @SWG\Property(property="meterial_id", type="integer", description="素材id"),
     *                      @SWG\Property(property="is_share", type="integer", description="0未分享， 1分享"),
     *                      @SWG\Property(property="target_interpush_id", type="integer", description="被分享用户id"),
     *                      @SWG\Property(property="target_is_share", type="integer", description="被动用户是否分享，1分享0位分享"),
     *                      @SWG\Property(property="target_share_time", type="integer", description="被动分享用户分享时间"),
     *                      @SWG\Property(property="inter_push_record_materials", type="object", description="主动用户素材",
     * @SWG\Property(property="article", type="object", description="文章article字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="author", type="integer", description="作者id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="personal_page_template_user", type="object", description="个人网页，personal_page_template_user字段实际中没有只是文档中作区分",
     *                           @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="user_marketing", type="object", description="营销网页，user_marketing字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="cards", type="object", description="名片cards，cards字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="head_picture", type="string", description="头像"),
     *                          @SWG\Property(property="logo", type="string", description="logo"),
     *                          @SWG\Property(property="user_name", type="string", description="用户名称"),
     *                          @SWG\Property(property="motto", type="string", description="封面"),
     *                          @SWG\Property(property="company", type="string", description="公司"),
     *                          @SWG\Property(property="sex", type="int", description="性别1男2女"),
     *                          @SWG\Property(property="province", type="int", description="省id"),
     *                          @SWG\Property(property="city", type="int", description="市id"),
     *                          @SWG\Property(property="area", type="int", description="区id"),
     *                          @SWG\Property(property="address_detail", type="string", description="详细地址"),
     *                      ),
     *                      ),@SWG\Property(property="passive_inter_push_record_materials", type="object", description="被动用户素材",
     * @SWG\Property(property="article", type="object", description="文章article字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="author", type="integer", description="作者id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="personal_page_template_user", type="object", description="个人网页，personal_page_template_user字段实际中没有只是文档中作区分",
     *                           @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="user_marketing", type="object", description="营销网页，user_marketing字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="template_id", type="integer", description="模板id"),
     *                          @SWG\Property(property="title", type="string", description="标题"),
     *                          @SWG\Property(property="content", type="string", description="内容"),
     *                          @SWG\Property(property="cover", type="string", description="封面"),
     *                      ),
     *                      @SWG\Property(property="cards", type="object", description="名片cards，cards字段实际中没有只是文档中作区分",
     *                          @SWG\Property(property="id", type="integer", description="id"),
     *                          @SWG\Property(property="head_picture", type="string", description="头像"),
     *                          @SWG\Property(property="logo", type="string", description="logo"),
     *                          @SWG\Property(property="user_name", type="string", description="用户名称"),
     *                          @SWG\Property(property="motto", type="string", description="封面"),
     *                          @SWG\Property(property="company", type="string", description="公司"),
     *                          @SWG\Property(property="sex", type="int", description="性别1男2女"),
     *                          @SWG\Property(property="province", type="int", description="省id"),
     *                          @SWG\Property(property="city", type="int", description="市id"),
     *                          @SWG\Property(property="area", type="int", description="区id"),
     *                          @SWG\Property(property="address_detail", type="string", description="详细地址"),
     *                          ),
     *                      ),
     *
     *                  )
     *          )
     *      )
     * )
     */
    public function getUserInterPushRecordList(Request $request)
    {
        $type = $request->input("type");
        $inter_push_info =  $this->user->interPushInfo();
        $records = [];
        switch ($type){
            // 相互分享
            case 1:
                $records = $inter_push_info
                    ->with(['interPushRecord' =>function($query){
                        $query->where(['is_share' => 1, "target_is_share" => 1]);
                    }, "passiveInterPushRecord" => function($query){
                        $query->where(['is_share' => 1, "target_is_share" => 1]);
                    },
                        "interPushRecord.passiveInterPushRecordMaterials",
                        "interPushRecord.interPushRecordMaterials",
                        "passiveInterPushRecord.interPushRecordMaterials",
                        "passiveInterPushRecord.passiveInterPushRecordMaterials",
                    ])
                    ->select("id","user_id", "province_id", "province", "use_num", "others_browse_num","is_enabled")
                    ->paginate (10);
                break;
                // 对方没有分享
            case 2:
                $records = $inter_push_info
                    ->with(['interPushRecord' =>function($query){
                        $query->where(['is_share' => 1, "target_is_share" => 0])->orderBy("created_at", "desc");
                    },
                        "interPushRecord.interPushRecordMaterials",
                        "interPushRecord.passiveInterPushRecordMaterials",
//                        "interPushRecord.interPushRecordMaterials",
//                        "interPushRecord.passiveInterPushRecordMaterials"
                    ])
                    ->select("id","user_id", "province_id", "province", "use_num", "others_browse_num","is_enabled")
                    ->paginate (10);
                break;
                // 我的分享任务
            case 3:
                $records = $inter_push_info
                    ->with(["passiveInterPushRecord" => function($query){
                        $query->where(['is_share' => 1, "target_is_share" => 0])->orderBy("created_at", "desc");
                    },"passiveInterPushRecord.interPushRecordMaterials"])
                    ->select("id","user_id", "province_id", "province", "use_num", "others_browse_num","is_enabled")
                    ->get();
                break;

        }
         return $this->renderJson ($records);
    }
    //endregion

    //region 分享被动匹配
    /**
     * @SWG\Put(
     *     path="/front/inter_push/passive_share/{id}",
     *     tags={"互推圈"},
     *     summary="分享被动匹配",
     *     description = "分享别人匹配我的记录",
     *      produces={"application/x-www-form-urlencoded"},
     *      @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="id", in="path", required=true, type="integer", description="互推记录id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功！",
     *     )
     * )
     */
    public function setPassiveUserInterPushShare($id)
    {
        $interPushInfo =  $this->user->interPushInfo;
        if ($interPushInfo->is_enabled == false){
            return $this->fail ("你没有开启互推圈，不能互推别人");
        }
        $interPushRecord = UserInterPushRecord::whereId ($id)->first();
        if ($interPushRecord->created_at->format("Y-m-d") < date ("Y-m-d", time ())){
            $record = UserInterPushRecord::whereRaw("DATE(`created_at`) < curdate()")->orderBy("created_at", "desc")->first();
            if ($record->id == $interPushRecord->id){
                // 设置reids
                if ($interPushInfo->province_id != 0){
                    $this->redis->sadd (date('Ymd')."_0_city" ,$interPushInfo->id);
                }
                $this->redis->sadd ($this->interPushCity,$interPushInfo->id); // 添加互推信息
                $this->redis->set($this->interPushNum, $interPushInfo->num); // 添加互推次数
            }
        }
        try{
            DB::beginTransaction ();
            $interPushRecord->target_is_share = 1;
            $interPushRecord->target_share_time = Carbon::now();
            $interPushRecord->save();
            DB::commit ();

        }catch (\Exception $exception){
            \Log::error ($exception);
            DB::rollBack();
            return $this->fail ("分享失败！");
        }
        return $this->success ("分享成功！");
    }

    //endregion

    //region 设置互推素材
    /**
     * @SWG\Put(
     *     path="/front/inter_push/info_material",
     *     tags={"互推圈"},
     *     summary = "设置素材",
     *     description = "设置素材",
     *     produces={"application/x-www-form-urlencoded"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="material_style", in="formData", required=false, type="integer", description="1,文章，2个人网页，3，营销网页，4，个人名片"),
     *     @SWG\Parameter(name="material_id", in="formData", required=false, type="integer", description="素材id,不用用户id"),
     *     @SWG\Parameter(name="province_id", in="formData", required=false, type="integer", description="地区id"),
     *     @SWG\Parameter(name="province", in="formData", required=false, type="integer", description="地区名称"),
     *     @SWG\Parameter(name="is_enabled", in="formData", required=false, type="integer", description="是否开启启用1， 0禁用"),
     *      @SWG\Response(
     *          response="200",
     *          description="调用成功！",
     *     )
     * )
     */
    public function setInfoMeterial(Request $request)
    {
        $material_style = $request->input ("material_style");
        $material_id = $request->input("material_id");
        $material = $this->getUserMeterial($material_style, $material_id);
        $interPushInfo =  $this->user->interPushInfo;

        // todo 素材跟换
        if ($request->input("material_id")){
            $interPushInfo->material_style = $material_style;
            $interPushInfo->material_id = $material_id;
            $interPushInfo->material_type = $material->getMorphClass();
        }
        // todo 更换地址
        if ($province = $request->input("province")){
            $interPushInfo->province = $province;
            $interPushInfo->province_id = $request->input("province_id");
            $this->interPushRedis($interPushInfo, $request->input ("province_id"));
        }
        $is_enabled =  $request->input("is_enabled");
        if (isset($is_enabled)){
            $interPushInfo->is_enabled = $is_enabled;
            $this->interPushIsEnabled($interPushInfo, $is_enabled);
        }
        $interPushInfo->save();
        return $this->success ("修改成功！");
    }
    //endregion
    //region 用户更改互推圈地址

    /**
     * 用户更改互推圈地址
     * @param UserInterPushInfo $interPushInfo
     * @param $province_id
     */
    private function interPushRedis($interPushInfo, $province_id)
    {
        // 判断redis 里面今天是否还有次数
        if ($this->redis->exists($this->interPushNum)){
            if ($interPushInfo->id != 0){
                $this->redis->srem ($this->interPushCity, $interPushInfo->id);
            }
            // 传入的值
            if ($province_id !=0 && $this->redis->sismember (date('Ymd')."_0_city",$interPushInfo->id) == 0){
                $this->redis->sadd (date('Ymd')."_0_city",$interPushInfo->id);
            }
            $this->redis->sadd(date('Ymd')."_".$province_id."_city",$interPushInfo->id);
        }
    }

    //endregion

    //region 用户互推圈启用|禁用
    /**
     * @param UserInterPushInfo $interPushInfo
     * @param $is_enabled
     */
    private function interPushIsEnabled($interPushInfo, $is_enabled)
    {
        // 关闭之后不能再使用redis集合去除
        if ($is_enabled == 0){
             // 禁用
            if ($interPushInfo->province_id != 0){
                $this->redis->srem (date('Ymd')."_0_city", $interPushInfo->id);
            }
            $this->redis->srem($this->interPushCity, $interPushInfo->id);
        }else{
            // 启用
            //判断用户今天使用次数
            if ($this->redis->exists($this->interPushNum) == true){

                if ($interPushInfo->province_id != 0) {
                    $this->redis->sadd ( date('Ymd')."_0_city", $interPushInfo->id );
                }

                $this->redis->sadd ( date ( 'Ymd' )."_". $interPushInfo->province_id . "_city", $interPushInfo->id );
            }else{
                // 如果没有 判断用户是否分享， 今天的次数是否用完
                $is_count =  $interPushInfo->passiveInterPushRecord()->whereRaw("DATE(`created_at`) < curdate()")->count();
                $to_day_count = $interPushInfo->passiveInterPushRecord ()->whereRaw("DATE(`created_at`) = curdate()")->count();
                if ($is_count <0 && $to_day_count < $interPushInfo->num){
                    if ($interPushInfo->province_id != 0) {
                        $this->redis->sadd ( date('Ymd')."_0_city", $interPushInfo->id );
                    }
                    $this->redis->sadd ( date ( 'Ymd' ) . $interPushInfo->province_id . "_city", $interPushInfo->id );
                    // 互推次数
                    $num = $interPushInfo->num - $to_day_count;
                    $this->redis->set($this->interPushNum, (int)$num);
                }
            }
        }
    }

    //endregion
    //region 添加用户互推消息
    /**
     * @SWG\Post(
     *       path="/front/inter_push/msg",
     *       tags={"互推圈"},
     *      summary="消息提醒！",
     *     description="消息提醒",
     *     produces={"application/form-data"},
     *     @SWG\Parameter(name="to_user_id", in="formData", required=true, type="integer", description="目标用户id"),
     *     @SWG\Parameter(name="user_name", in="formData", required=true, type="integer",description="登录用户名称"),
     *     @SWG\Response(
     *          response="200",
     *          description="提醒成功"
     *      )
     * )
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     */
    public function saveMsg(Request $request)
    {
        $this->validate ($request, [
            'to_user_id' => "required"
        ],[
            'to_user_id.required' => '内容不能为空'
        ]);

        $title ='互推圈消息！';
        $user_name =  $request->input("user_name");
        $to_user_id = $request->input("to_user_id");
        $user_msg =  UserMsg::where(["from_user_id"=> $this->user->id, "to_user_id"=> $to_user_id, 'type' => 2])
                            ->whereRaw("DATE(`created_at`) = curdate() ")
                            ->first();

        if (isset($user_msg) && $user_msg->created_at->format("Y-m-d") == date ("Y-m-d", time())){
            return $this->fail("今天已经提醒过了，不能重复提醒！");
        }


        $res =  UserMsg::add ($title, $user_name."提醒你完成互推圈任务",2,$this->user->id,$to_user_id);
        if (!$res){
            return $this->error ("提醒失败！");
        }
        return $this->success ("提醒成功！");
    }

    //endregion



    //region 获取用户素材
    /**
     * 获取用户素材
     * @param $material_style
     * @param $material_id
     * @return Articles|Cards|PersonalPageTemplateUser|UserMarketing|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     */
    public function getUserMeterial($material_style, $material_id)
    {
        switch ($material_style){
            case 1:
                if ($material_id){
                    return Articles::whereId ($material_id)->first();
                }
                return Articles::take(1)->first();
                break;
            case 2:
                return PersonalPageTemplateUser::whereId($material_id)->first();
                break;
            case 3:
                return UserMarketing::whereId($material_id)->first();
                break;
            case 4:
                return Cards::whereId($material_id)->first();
                break;
        }

    }
    // endregion

}
